import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { timeFormat } from '/@/utils/filters';
import { getCommonSiteList, getCurrencyUnit, getSiteNameByShorthand } from '/@/utils/commonRequest';
import useCouponState from '/@/utils/pageState/couponState';
import { useCouponApi } from '/@/api/coupon';
export function useCouponHook() {
	const { COUPON_STATUS_LIST, FULL_MINUS, getCouponStatusText, getPreferentialamount } = useCouponState();
	const { EndCoupon, getCouponList } = useCouponApi();
	const couponDetailRef = ref();
	const state = reactive({
		isShowCouponDialog: false,
		formData: {
			state: '', // "" 全部
			time: [null, null],
		},
		tableData: [],
		page: {
			current: 1,
			pageSize: 10,
			total: 0,
		},
		loading: ref(false),
		checkCouponId: ref(-1),
	});
	const $route = useRoute();
	const router = useRouter();

	function init() {
		if ($route.query.id) {
			state.checkCouponId = Number($route.query.id);
		}
		getList();
		getCommonSiteList();
	}

	function searchFun() {
		state.page = {
			pageSize: state.page.pageSize,
			current: 1,
			total: state.page.total,
		};
		getList();
	}

	async function getList() {
		if (state.loading) {
			return;
		}
		state.loading = true;

		try {
			let params = {
				current: state.page.current,
				pageSize: state.page.pageSize,
				status: state.formData.state,
				startTime: state.formData.time
					? state.formData.time[0] === null
						? null
						: dayjs(state.formData.time[0]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
					: null,
				endTime: state.formData.time
					? state.formData.time[1] === null
						? null
						: dayjs(state.formData.time[1]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
					: null,
			};
			if (state.formData.time === null) {
				params.startTime = null;
				params.endTime = null;
			}
			let res = await getCouponList(params);
			if (res.code !== 200) {
				state.loading = false;
				return;
			}
			state.loading = false;
			state.page = {
				pageSize: res.data.pageSize,
				current: res.data.current,
				total: res.data.total,
			};

			let tempList = [];
			if (res.data.length !== 0) {
				tempList = res.data.data.map((item, index) => {
					console.log('item.type', item.type);
					return {
						id: item.couponId,
						orderNumber: (res.data.current - 1) * 10 + index + 1,
						couponName: item.name,
						couponCode: item.code,
						preferentialAmount: getPreferentialamount(item.type, item.discount ? item.discount * 10 : item.amount),
						useSites: getSiteNameByShorthand(item.platformCode),
						used: item.useCount ? item.useCount : 0,
						totalPreferentialAmount: item.type === FULL_MINUS ? getCurrencyUnit(item.platformCode) + item.amountNum : '消费满1件享受折扣',
						startDate: timeFormat(item.startTime),
						endDate: timeFormat(item.endTime),
						state: getCouponStatusText(item.status),
					};
				});
			}
			state.tableData = tempList;
		} catch (error) {
			state.loading = false;
			console.error(error);
			ElMessage({
				type: 'error',
				message: '获取优惠券列表失败',
			});
		}
	}

	// 结束的询问
	function beforeDelete(item) {
		// 提示是否结束
		ElMessageBox.confirm(`确认结束优惠券${item.couponName}？`, '结束优惠券', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(() => {
				delFun(item.id);
			})
			.catch(() => {});
	}

	// 结束
	async function delFun(id) {
		if (state.loading) {
			return;
		}
		state.loading = true;

		try {
			let res = await EndCoupon(id);
			if (res.code !== 200) {
				state.loading = false;
				return;
			}
			state.loading = false;
			ElMessage({
				type: 'success',
				message: '结束成功',
			});
			getList();
		} catch (error) {
			state.loading = false;
			ElMessage({
				type: 'error',
				message: '结束失败',
			});
		}
	}

	// 设置详情的id
	function setDetailId(id) {
		router.push({ name: 'MarketingCouponDetail', params: { id } });
		state.checkCouponId = id;
		// state.isShowCouponDialog = true;
	}

	const cancel = () => {
		couponDetailRef.value.cancel();
		state.isShowCouponDialog = false;
	};

	const onSaveCoupon = () => {
		couponDetailRef.value.submitForm();
		setTimeout(() => {
			state.isShowCouponDialog = false;
		}, 500);
	};

	// 分页改变
	const onHandleSizeChange = (val) => {
		state.page.pageSize = val;
	};
	// 分页改变
	const onHandleCurrentChange = (val) => {
		state.page.current = val;
		getList();
	};

	return {
		couponDetailRef,
		COUPON_STATUS_LIST,
		state,
		init,
		searchFun,
		beforeDelete,
		setDetailId,
		cancel,
		onSaveCoupon,
		onHandleSizeChange,
		onHandleCurrentChange,
	};
}
